//
//  FootPrintVc.swift
//  Pods
//
//  Created by eme on 2017/3/31.
//
//

import UIKit
import UtilCore
import RxSwift
import AddCarCore
import RickonCore
import EmptyDataView
import BrandonCore

class FootPrintVc: Empty_TVc,AddCarProtocol {
    
    /****************************Storyboard UI设置区域****************************/
    @IBOutlet weak var customTableView: UITableView!
    
    @IBOutlet weak var collectButton: UIButton!                         //删除按钮
    
    @IBOutlet weak var customTableViewBottom: NSLayoutConstraint!
    
    /*----------------------------   自定义属性区域    ----------------------------*/
    var datArray:[FootPrintModel]?{
        didSet{
            self.customTableView.reloadData()
            
            if self.datArray?.count != 0{
                
                self.buttonWithEditor.isHidden = false
            }
        }
    }
    
    var isChange = false
    
    var fpvm:FootPrintViewModel! = nil
    
    let hearder = MJRefreshNormalHeader()
    
    var countArr = [Int]()
    
    
    //    let footer = MJRefreshAutoNormalFooter()
    
    let buttonWithEditor = UIButton(type:.system)
    
    var GetSku:GetSkuVm?                                            //获取商品列表(在这里是获取SKU的)
    
    /****************************Storyboard 绑定方法区域****************************/
    @IBAction func deleteFootPrint(_ sender: UIButton) {
        var cdidArr = [String]()
        var cdid = ""
        for model in datArray!{
            for list in model.list{
                if list.isclicked == 1{
                    cdidArr.append("\(list.fid)")
                    cdid = cdidArr.joined(separator: ",")
                }
            }
            
        }
        self.fpvm.deleteFootPrint.onNext(cdid)
    }
    /*
     * 加入铺货单
     */
    @IBAction func add_JHD(_ sender: UIButton) {
        if let _ = AppData.loginedUser{
            if case AppDataState.audited = AppData.appState{
                self.GetSku?.getSKU.onNext("\((self.datArray?[(sender.imageView?.tag)!].list[sender.tag].pdid)!)")
            }else{
                _ = "authvalidation".openURL(["isneedlogin":"1"])
            }
        }else{
            _ = "login".openURL()
        }
        
    }
    
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.setNavigationBarHidden(false, animated: true)
        if self.datArray?.count == 0{
            
            self.buttonWithEditor.isHidden = true
        }
        collectButton.titleLabel?.bold_fontSize(15)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
        self.tabBarController?.tabBar.isHidden = true
        self.fpvm.getFootPrintList.onNext("getFootPrintList")
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        self.customLeftBarButtonItem()
        hearder.setRefreshingTarget(self, refreshingAction: #selector(FootPrintVc.brandHeaderRefresh))
        self.customTableView.mj_header = hearder
        
        // 下拉加载更多
        //        footer.setRefreshingTarget(self, refreshingAction: #selector(Collect_Vc.brandFooterRefresh))
        //        footer.automaticallyHidden = true
        //        self.brand_TableView.mj_footer = footer
        
        
        customTableView.dzn_tv_emptyDataSource = self
        customTableView.dzn_tv_emptyDelegate = self
        
        self.customLeftBarButtonItem()
        self.setUpTableView()
        self.setTheEditorButton()
        self.setUpTableViewBottom()
        self.setUpDeleteBtn()
    }
    func setUpTableView(){
        
        self.customTableView.showsVerticalScrollIndicator = false
        customTableView.dataSource = self
        customTableView.delegate = self
    }
    func setTheEditorButton(){
        
        
        buttonWithEditor.frame = CGRect(x:0,y:0,width: 40,height: 15)
        buttonWithEditor.setTitle("编辑", for: .normal)
        buttonWithEditor.addTarget(self, action: #selector(FootPrintVc.editorBrandOrGoods(_:)), for: .touchUpInside)
        let editorButton = UIBarButtonItem(customView: buttonWithEditor)
        self.navigationItem.rightBarButtonItem = editorButton
    }
    //编辑按钮点击方法
    func editorBrandOrGoods(_ sender:UIButton){
        
        self.collectButton.isEnabled = false
        
        if isChange == false{
            sender.setTitle("完成", for: .normal)
            isChange = true
            self.collectButton.isHidden = false
            customTableViewBottom.constant = 0
            
        }else{
            sender.setTitle("编辑", for: .normal)
            isChange = false
            self.collectButton.isHidden = true
            customTableViewBottom.constant = -49
            for model in datArray!{
                
                model.isclicked = 0
                
                for cellmodel in model.list{
                    
                    cellmodel.isclicked = 0
                }
            }
            
        }
        
        self.customTableView.reloadData()
        
    }
    /**
     区头点击事件(全部选中)
     */

    func selectHeaderCell(_ sender:UIButton){
        
        if datArray?[sender.tag].isclicked == 0{
            
            datArray?[sender.tag].isclicked = 1
            
            for model in (datArray?[sender.tag].list)!{
                
                model.isclicked = 1
            }
            
        }else{
            
            datArray?[sender.tag].isclicked = 0
            
            for model in datArray![sender.tag].list{
                
                model.isclicked = 0
            }
            
        }
        var numArr = [Int]()
        for model in datArray!{
            for list in model.list{
                numArr.append(list.isclicked)
            }
        }
        if numArr.contains(1) == true{
            self.collectButton.isEnabled = true
        }else{
            self.collectButton.isEnabled = false
        }
        self.customTableView.reloadData()
        
    }
    /**
     设置删除按钮隐藏并且 表距离按钮 顶部 为-49
     */
    func setUpTableViewBottom(){
        self.collectButton.isHidden = true
        customTableViewBottom.constant = -49
    }
    func setUpDeleteBtn(){
    
        self.collectButton.setBackgroundImage(Theme.sansa.footPrint.Footprint_Default_Btn.getImage(), for: .normal)
        self.collectButton.setBackgroundImage(Theme.sansa.footPrint.Footprint_highlighted_Btn.getImage(), for: .highlighted)
        self.collectButton.setBackgroundImage(Theme.sansa.footPrint.Footprint_Disable.getImage(), for: .disabled)
    }
    
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        //
        
        self.fpvm = FootPrintViewModel()
        
        self.fpvm.footListModel
            .asObservable()
            .do(onNext:{[unowned self] _ in
                
                self.errorPageView.isHidden = true
                
            }).subscribe(onNext:{ list in
                
                self.showEmptyView = true
                self.datArray = list
                
            }).addDisposableTo(disposeBag)
        
        
        self.fpvm.loading.asObservable().bindTo(self.view.rx_loading).addDisposableTo(disposeBag)
        self.fpvm.refresherror.asObserver().bindTo(self.rx_showerrorpage).addDisposableTo(disposeBag)
        self.fpvm.error.asObserver().bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        self.errorPageView.reloadSubject.bindTo(self.fpvm.reloadTrigger).addDisposableTo(disposeBag)
        
        self.fpvm.deleteBackData.subscribe(onNext:{ list in
            
            self.showEmptyView = true
            self.datArray = list
            self.view.toast("删除成功")
            
            if list.count == 0{
                self.collectButton.isHidden = true
                self.buttonWithEditor.isHidden = true
            }else{
                self.buttonWithEditor.isHidden = false
                self.collectButton.isHidden = false
                self.collectButton.isEnabled = false
            }
            
            
        }).addDisposableTo(disposeBag)
        
        
        
        //======加入铺货单
        self.GetSku = GetSkuVm()
        
//        let manageVm = Add_shoppingCartVm()
        
        self.GetSku?.backSkuDate.asObserver().subscribe(onNext:{ result in
            
            self.addCar(vc: self, model: result,footerButonType:"jrphd"){ product , param,_ in
                self.GetSku?.addcartsSubject.onNext(param["osCarts"] as! String as NSString)
            }
            
        }).addDisposableTo(disposeBag)
        
        self.GetSku?.addcartsSuccess.subscribe(onNext:{ data in
            
            _ = "orderformbadge".openURL()
            
            self.view.toastErrorCode(100041002)
//            showSuccessMsg(alertmsg[100041002]?.msgtitle)
            
            }).addDisposableTo(disposeBag)
        
        self.GetSku?.error.bindTo(self.view.rx_error).addDisposableTo(disposeBag)
    }
    //-------
    //下拉刷新
    func brandHeaderRefresh(){
        
        self.fpvm.getFootPrintList.onNext("getFootPrintList")
        self.hearder.endRefreshing()
    }
}
extension FootPrintVc:UITableViewDelegate,UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        if let arr = datArray{
            return arr.count
        }else{
            return 0
        }
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let arr = datArray?[section].list{
            return arr.count
        }else{
            return 0
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! FootPrintTableViewCell
        cell.addJHD_Button.tag = indexPath.row
        cell.addJHD_Button.imageView?.tag = indexPath.section
        cell.item = self.datArray![indexPath.section].list[indexPath.row]
        if isChange == true{
            cell.addJHD_Button.isHidden = true
            cell.clickedImageView.isHidden = false
            cell.leftWithimage.constant = 6
            
            if datArray![indexPath.section].list[indexPath.row].isclicked == 0{
                
                cell.clickedImageView.image = UIImage(named: "not clicked", in: SansaCore.bundle, compatibleWith: nil)
                
            }else{
                
                cell.clickedImageView.image = UIImage(named: "The selected", in: SansaCore.bundle, compatibleWith: nil)
            }
            
        }else{
            
            
            cell.addJHD_Button.isHidden = false
            cell.clickedImageView.isHidden = true
            cell.leftWithimage.constant = -17
        }
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 125
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let cell = tableView.dequeueReusableCell(withIdentifier: "dateCell") as! FootPrintDateTableViewCell
        cell.item = self.datArray?[section]
        
        if isChange == true{
            cell.isClicked.isHidden = false
            cell.leftwithImage.constant = 10
            
            cell.headerButton.addTarget(self, action: #selector(FootPrintVc.selectHeaderCell(_:)), for: .touchUpInside)
            cell.headerButton.tag = section
            
            
            if datArray?[section].isclicked == 0{
                
                cell.isClicked.image = UIImage(named: "not clicked", in: SansaCore.bundle, compatibleWith: nil)
                
            }else{
                cell.isClicked.image = UIImage(named: "The selected", in: SansaCore.bundle, compatibleWith: nil)
                
            }
            
        }else{
            
            cell.isClicked.isHidden = true
            cell.leftwithImage.constant = -17
        }
        
        return cell
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 25
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if isChange == true{
            
            if datArray![indexPath.section].isclicked == 0{
                
                if datArray![indexPath.section].list[indexPath.row].isclicked == 0{
                    
                    datArray![indexPath.section].list[indexPath.row].isclicked = 1
                    
                }else{
                    
                    datArray![indexPath.section].list[indexPath.row].isclicked = 0
                    
                }
                
            }else{
                
                datArray![indexPath.section].isclicked = 0
                datArray![indexPath.section].list[indexPath.row].isclicked = 0
                
            }
            //-----------
            //判断是否全选
            self.countArr.removeAll()
            for model in datArray![indexPath.section].list{
                self.countArr.append(model.isclicked)
            }
            if self.countArr.contains(0) == false{
                self.datArray![indexPath.section].isclicked = 1
            }
            //-------
            //是否删除按钮是否可以点击
            var numArr = [Int]()
            for model in datArray!{
                for list in model.list{
                    numArr.append(list.isclicked)
                }
            }
            if numArr.contains(1) == true{
                self.collectButton.isEnabled = true
            }else{
                self.collectButton.isEnabled = false
            }
            //------------------------------------------------------!!!!
            self.customTableView.reloadData()
            
        }else{
            _ = "productdetail".openURL(["pdid":"\(datArray![indexPath.section].list[indexPath.row].pdid)"])
        }
        
        
    }
}
extension FootPrintVc:EmptyDataSource{
    func description(emptyView scrollView: UIScrollView) -> NSAttributedString? {
        return Theme.getEmptyDesc("你还没有足迹\n快去逛逛吧")
    }
    func image(emptyView scrollView: UIScrollView) -> UIImage? {
        return UIImage.init(named: "footpring_empty", in: SansaCore.bundle, compatibleWith: nil)
    }
    func backgroundColor(emptyView scrollView: UIScrollView) -> UIColor?{
        return UIColor.white
    }
}
